package com.foreknow.dao.impl;

import com.foreknow.dao.UserDao;
import com.foreknow.entity.User;
import com.foreknow.util.DbHelper;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;
import java.util.List;

public class TestImpl implements UserDao {
    @Override
    public boolean userInsert(User user) throws SQLException {
        QueryRunner qr = new QueryRunner(DbHelper.getDataSource());
        String sql = "insert into user(username,account,password,phone,email,avater) values(?,?,?,?,?,?)";
        int isRight =  qr.update(sql,user.getUsername(),user.getAccount(),user.getPassword(),user.getPhone(),user.getEmail(),user.getAvater());
        return isRight==1;
    }

    @Override
    public boolean userUpdate(User user) throws SQLException {
        QueryRunner qr = new QueryRunner(DbHelper.getDataSource());
        String sql = "update user set username=?,account=?,password=?,phone=?,email=?,avater=? WHERE id=?";
        int isRight =  qr.update(sql,user.getUsername(),user.getAccount(),user.getPassword(),user.getPhone(),user.getEmail(),user.getAvater(),user.getId());
        return isRight==1;
    }

    @Override
    public boolean userDelete(Integer id) throws SQLException {
        QueryRunner qr = new QueryRunner(DbHelper.getDataSource());
        String sql = "delete from user where id = ?";
        int isRight = qr.update(sql,id);
        return isRight==1;
    }

    @Override
    public List<Object[]> userSelectAll() throws SQLException {
        QueryRunner qr = new QueryRunner(DbHelper.getDataSource());
        String sql ="select * from user";
        List<Object[]> list = qr.query(sql, new ArrayListHandler());
        return list;
    }

    @Override
    public User userSelect(String username) throws SQLException {
        QueryRunner qr = new QueryRunner(DbHelper.getDataSource());
        String sql ="select * from user where username = ?";
        User user = qr.query(sql,new BeanHandler<User>(User.class),username);
        return user;
    }
}
